package com.aaa.springboot.controller;

import com.aaa.springboot.commons.lang.Result;
import com.aaa.springboot.dao.PermissionDao;
import com.aaa.springboot.dao.RoleDao;
import com.aaa.springboot.dao.RolePermissionDao;
import com.aaa.springboot.dao.UserRoleDao;
import com.aaa.springboot.pojo.Permission;
import com.aaa.springboot.pojo.RolePermission;
import com.aaa.springboot.pojo.TUser;
import com.aaa.springboot.pojo.UserRole;
import com.aaa.springboot.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.security.PermitAll;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
public class RegisterController {


    @Autowired
    private UserService userService;


    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private RolePermissionDao rolePermissionDao;

    @Autowired
    private PermissionDao permissionDao;


    @PostMapping("register")
    public Result register(TUser tUser) {
        log.info("用户:{}", tUser);
        // 使用hash加密
        String password = BCrypt.hashpw(tUser.getPassword(), BCrypt.gensalt());
        tUser.setPassword(password);
        int i = userService.insertSelective(tUser);
        if (i > 0) {
            // 增加成功 ，进行给用户进行授权
            // 根据用户名查询出用户id
            TUser tUser1 = userService.selectByUsernameTUser(tUser.getUsername());
            // 用户Id
            Long userId=tUser1.getId();
            // 查询角色  默认给一个经理
            UserRole record = new UserRole();
            record.setCreateTime(new Date());
            record.setRoleId(2L);
            record.setUpdateTime(new Date());
            record.setUserId(userId);
            // 添加到用户角色中间表中
            int i1 = userRoleDao.insertSelective(record);
            //
            if (i1>0){
               Long roleId=2L;
                List<Permission> permissions = permissionDao.selectALl();
                permissions.forEach(permission -> {
                    RolePermission record1 = new RolePermission();
                    record1.setRoleId(roleId);
                    record1.setPermissonId(permission.getId());
                    rolePermissionDao.insertSelective(record1);
                });
                return Result.ok();
            }


        }
        return Result.fail();
    }
}
